package com.bjgzy.rating.mvp.presenter;

import android.app.Application;

import com.bjgzy.rating.mvp.contract.EntriesContract;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.EntriesData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-8-7 17:12:55
 */
@FragmentScope
public class EntriesPresenter extends BasePresenter<EntriesContract.Model, EntriesContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    BaseQuickAdapter<EntriesData, AutoBaseViewHolder> mAdapter;

    private int page = 1;
    private int pageSize = 10;

    @Inject
    public EntriesPresenter(EntriesContract.Model model, EntriesContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }


    public void getWorksByResearchId(boolean pullToRefresh, int researchId) {
        if (pullToRefresh) {
            page = 1;
        } else {
            page++;
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("researchId", researchId);
        map.put("pageNo", page);
        map.put("pageSize", pageSize);
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        mModel.getWorksByResearchId(map)
                .retryWhen(new RetryWithDelay(2, 3))
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        if (pullToRefresh)
                            mRootView.showLoading();//显示进度条
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(new Action() {
                    @Override
                    public void run() {
                        if (pullToRefresh)
                            mRootView.hideLoading();//隐藏进度条
                    }
                }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<List<EntriesData>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<EntriesData>> data) {
                        if (data.isResult()) {
                            if (pullToRefresh) {
                                if (mAdapter.getFooterLayoutCount() > 0) {
                                    mAdapter.removeAllFooterView();
                                }
                                mAdapter.setNewData(data.getData());
                            } else {
                                mAdapter.addData(data.getData());
                            }
                            if (data.getData().size() < pageSize) {
                                mAdapter.loadMoreEnd(true);
                                mRootView.addFooter();
                            } else {
                                mAdapter.loadMoreComplete();
                            }
                        } else {
                            mRootView.showMessage(data.getMessage());
                        }
                        if (ObjectUtils.isEmpty(data.getData()) && ObjectUtils.isEmpty(mAdapter.getData())) {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_data));
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (pullToRefresh) {
                            if (t instanceof ConnectException || t instanceof UnknownHostException) {
                                mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_network));
                            } else {
                                mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.load_error));
                            }
                        } else {
                            mAdapter.loadMoreFail();
                        }
                    }
                });
    }

    public void saveVote(int worksId, int position) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("worksId", worksId);
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        mModel.saveVote(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        mRootView.showMessage(commonData.getMessage());
                        if (commonData.isResult()) {
                            EntriesData data = mAdapter.getData().get(position);
                            data.setVoteCount(data.getVoteCount() + 1);
                            mAdapter.notifyItemChanged(position);
                        } else {
                        }
                    }
                });
    }
}
